<template>
  <a-table
    style="margin-bottom: 0px;margin-top: 5px"
    rowKey="id"
    bordered
    size="middle"
    tableLayout="auto"
    :scroll="{ x: 900 }"
    :columns="columns"
    :pagination="false"
    :dataSource="dataSource"
  >
  </a-table>
</template>

<script>
  import { getReportColumns, getReportDataSource } from '@/api/api'
  import { getAction } from '@/api/manage'

  export default {
    name: "JReportTable",
    props: {
      code: String,
      startTime: String,
      endTime: String,
      version: Number,
      storeId: String,
    },
    data() {
      return {
        columns: [],
        totalColumn: {
          title: '#',
            width: '100px',
          align: 'center',
          dataIndex: 'rowIndex',
          customRender: function (text, r, index) {
            return (text !== '合计') ? (parseInt(index) + 1) : text
          }
        },
        dataSource: [],
        _version : -1
      }
    },
    watch:{
      version: {
        immediate: true,
        handler(val) {
          console.log("version",this.version);
          if(this.version !== this._version){
            this._version = this.version;
            this.initColumnsData()
          }
        }
      }
    },
    created() {

    },
    mounted() {
      //this.tableAddTotalRow(this.columns, this.dataSource)

    },

    methods: {
      /*onmousedown(event){
        let el = this.$el.querySelector('table');
        event.stopPropagation();
        let disx = event.clientX;
        document.onmousemove = function (e){
          e.preventDefault();
          let offset = e.clientX - disx;
          el.scrollLeft = offset;
        }
        document.onmouseup = function(){
          document.onmousemove = document.onmouseup = null;
        }
      },*/
      initColumnsData() {
        if (this.code) {
          //console.log("code",this.code);
          getReportColumns({code:this.code}).then((res) => {
            if (res.success) {
              var cols = JSON.parse( res.result.columns );
              this.formatColumns(cols);
              cols.unshift(this.totalColumn);
              this.columns = cols;
              this.loadDataSourceData();
            }
          })
        }
      },
      formatColumns(columns) {
        columns.forEach(c=>{

          if(c.hasOwnProperty("children") == true){
            this.formatColumns(c.children);
          } else {
            if (c._type==='price' || c._type==='unitprice'){
              c.customRender = function (t,r,index) {
                let v = '' + t.toFixed(2);
                return v==='0.00' ? '0' : v;
              }
              c.sorter = function (a, b) {
                if (a.rowIndex === '合计') {
                  return 0;
                }
                return a[c.dataIndex] - b[c.dataIndex];
              }
              c.sortDirections = ['ascend', 'descend']
            }else if (c._type==='rate'){
              c.customRender = function (t,r,index) {
                return t.toFixed(2) + '%';
              }
              c.sorter = function (a, b) {
                if (a.rowIndex === '合计') {
                  return 0;
                }
                return a[c.dataIndex] - b[c.dataIndex];
              }
              c.sortDirections = ['ascend', 'descend']
            }else if (c._type==='number') {
              c.sorter = function (a, b) {
                if (a.rowIndex === '合计') {
                  return 0;
                }
                return a[c.dataIndex] - b[c.dataIndex];
              }
              c.sortDirections = ['ascend', 'descend']
            }
          }
        });
      },
      loadDataSourceData() {
        getReportDataSource({code:this.code,startTime:this.startTime,endTime:this.endTime,storeId:this.storeId}).then((res) => {
          if (res.success) {
            let list = res.result;
            let numKey = 'rowIndex'
            let totalRow = { [numKey]: '合计' }
            if (res.result.length>0){
              this.tableAddTotalRow(this.columns, res.result, totalRow);
              list.push(totalRow);
            }
            this.dataSource = list;
          }
        })
      },
      /** 表格增加合计行 */
      tableAddTotalRow(columns, dataSource, totalRow) {
        columns.forEach(column => {
          let { _type, dataIndex } = column
          if(column.hasOwnProperty("children") == true){
            this.tableAddTotalRow(column.children, dataSource, totalRow);
          } else {
            if (dataIndex!='rowIndex')
              switch (_type){
                case 'price':
                case 'number':
                  totalRow[dataIndex] = dataSource.map((data)=>{return /^\d+\.?\d*$/.test(data[dataIndex]) ? Number.parseFloat(data[dataIndex]) : 0.0}).reduce((a,b)=>a+b, 0);
                  break;
                case 'unitprice':
                case 'rate':
                  totalRow[dataIndex] = (dataSource.map((data)=>{return /^\d+\.?\d*$/.test(data[dataIndex]) ? Number.parseFloat(data[dataIndex]) : 0.0}).reduce((a,b)=>a+b, 0))/dataSource.length;
                  break;
                default : totalRow[dataIndex] = '';
                  break;
              }
          }
        })
        /*dataSource.push(totalRow)
        return dataSource;*/
      }
    }
  }
</script>

<style scoped>
</style>